import React, { useEffect, useState, useRef } from "react";
import ReactMarkdown from 'react-markdown';
import {
  Button,
  Select,
  Input,
  message,
} from "antd";
import {
  UploadOutlined,
  StopOutlined
} from "@ant-design/icons";
import { datetimeFormat } from "@/utils/dateUtils";
import type { MenuProps } from 'antd';
import "./index.less";
import { useDispatch } from "react-redux";
import { storeChatList } from "@/stores/actions";



function index() {

  const ollamaRemote = 'http://localhost:11434/api'

  const { TextArea } = Input;

  const [selectedFile, setSelectedFile] = useState([]) 

  const [modelList, setModelList] = useState([]);

  const [currentModel, setCurrentModel] = useState<string>()

  const [isLoading, setIsLoading] = useState(false); // 加载状态

  const [thinking, setThinking] = useState(false);
  
  const [thinked, setThinked] = useState(true);

  const [prompt, setPrompt] = useState<string>("")

  const [chatList, setChatList] = useState<any>([])

  const abortControllerRef = useRef(null);

  const chatAreaRef = useRef(null);

  const dispatch = useDispatch();


  useEffect(() => {
    loadModelList();
  }, []);

  useEffect(() => {
    // 确保容器已挂载
    if (chatAreaRef.current) {
      const container = chatAreaRef.current;
      // const { scrollTop, clientHeight, scrollHeight } = chatAreaRef.current;
      // console.log(container.scrollTop, container.scrollHeight)
      // 关键：将滚动条位置设置为内容总高度
      if (container.scrollTop + container.clientHeight >= container.scrollHeight - 40) {
        container.scrollTop = container.scrollHeight;
      }
    }
  }, [chatList]);

  const loadModelList = async () => {
    try {
      const response = await fetch(`${ollamaRemote}/tags`);
      if (!response.ok) throw new Error('获取模型列表失败');
      
      const data = await response.json();

      let models = data.models.map(item => {
        return {
          value: item.model,
          label: item.model
        }
      })
      setModelList(models || []);
      // 默认选中第一个模型
      if (models?.length > 0) {
        setCurrentModel(models[0].value);
      }
    } catch (err) {
      message.error(`初始化失败: ${err.message}（请确保 Ollama 服务已启动）`)
    }
  }

  const changeModel = (model: any) => {
    console.log("model: ", model)
    setCurrentModel(model)
  }

  const sendMessage = async () => {
    setThinked(false)
    // 添加用户消息到列表
    const userMessage = {
      id: Date.now(),
      role: 'user',
      content: prompt.trim()
    };
    setChatList((prev: any) => [...prev, userMessage]);
    
    // 准备助手消息（初始为空，后续流式填充）
    const assistantMessageId = Date.now() + 1;
    setChatList(prev => [
      ...prev, 
      { id: assistantMessageId, role: 'assistant', content: '', isComplete: false }
    ]);
    
    // 清空输入框并设置加载状态
    setPrompt('');
    setIsLoading(true);

    // 取消可能存在的未完成请求
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }
    const abortController = new AbortController();
    abortControllerRef.current = abortController;

    try {
      // 调用 Ollama chat API（流式）
      const response = await fetch(`${ollamaRemote}/chat`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          model: currentModel,
          messages: chatList.concat(userMessage).map(({ id, answer, thinking, ...rest }) => rest), // 过滤掉id,拆分后的思考，回答
          stream: true,
          keep_alive: '5m'
        }),
        signal: abortController.signal
      });

      if (!response.ok) throw new Error(`请求失败: ${response.status}`);
      if (!response.body) throw new Error('无响应内容');

      // 处理流式响应
      const reader = response.body.getReader();
      await handleStreamResponse(reader, assistantMessageId);

    } catch (err) {
      if (err.name !== 'AbortError') { // 忽略主动取消的错误
        message.error(`发送失败: ${err.message}`);
        console.error(err);
        // 移除未完成的助手消息
        setChatList(prev => prev.filter(msg => msg.id !== assistantMessageId));
        setIsLoading(false);
        setThinking(false);
      }
    }
  };

  const cancelRequest = () => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
      setIsLoading(false);
      setThinking(false);
      // 标记最后一条助手消息为已取消
      setChatList(prev => 
        prev.map(msg => 
          msg.role === 'assistant' && !msg.isComplete 
            ? { ...msg, content: msg.content + '（已取消）', isComplete: true } 
            : msg
        )
      );
    }
  };

  const handleStreamResponse = async (reader, assistantMessageId) => {
    console.log("解析回答")
    setThinked(true)
    const decoder = new TextDecoder();
    let tempThinking = thinking
    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        // 流式结束，更新消息状态（标记为完成）
        setChatList(prev => 
          prev.map(msg => 
            msg.id === assistantMessageId ? { ...msg, isComplete: true } : msg
          )
        );
        setIsLoading(false);
        setThinking(false);
        break;
      }

      // 解析流式数据（每行是一个 JSON 对象）
      const chunk = decoder.decode(value, { stream: true });
      const lines = chunk.split('\n').filter(line => line.trim());
      
      for (const line of lines) {
        try {
          const data = JSON.parse(line);
          console.log("message: ", data.message.content)
          if (data.message?.content) {
            if (data.message.content == '<think>') {
              // 开始思考
              tempThinking = true
              setThinking(tempThinking)
              setChatList(prev => 
                prev.map(msg => 
                  msg.id === assistantMessageId
                    ? { ...msg, thinking: '**Thinking:** ' } 
                    : msg
                )
              );
              continue
            }
            
            if (data.message.content == '</think>') {
              // 结束思考
              tempThinking = false
              setThinking(tempThinking)
              continue
            }
            if (tempThinking) {
              setChatList(prev => 
                prev.map(msg => 
                  msg.id === assistantMessageId
                    ? { ...msg, thinking: msg.thinking ? msg.thinking + data.message.content : data.message.content } 
                    : msg
                )
              );
            } else {
              console.log("answer: ", data.message.content)
              setChatList(prev => 
                prev.map(msg => 
                  msg.id === assistantMessageId
                    ? { ...msg, answer: msg.answer ? msg.answer + data.message.content : data.message.content } 
                    : msg
                )
              );
            }

            // 实时更新助手消息内容
            setChatList(prev => 
              prev.map(msg => 
                msg.id === assistantMessageId 
                  ? { ...msg, content: msg.content + data.message.content } 
                  : msg
              )
            );
          }
        } catch (parseErr) {
          console.error('解析流式数据失败:', parseErr);
        }
      }
    }
    // dispatch(storeChatList(chatList))
  };

  const renderChatArea = () => {
    return chatList.map((item, index)=> {
      return (<>
        <div className={item.role === 'user' ? 'user-chat' : 'assisstant-chat'}>
          {
            item.role === 'user' ? (
              <>
                <div><ReactMarkdown>{item.content}</ReactMarkdown></div>
              </>
            ) : (
                thinked || index + 1 != chatList.length? (<>
                  <div className="think-area">
                    <ReactMarkdown>{item.thinking}</ReactMarkdown>
                  </div>
                  {
                    item.answer ? (
                      <div className="answer-area">
                        <ReactMarkdown>{item.answer}</ReactMarkdown>
                      </div>
                    ) : (<></>)
                  }
                </>) : (
                  <div className = "centered">
                    <div className = "blob-1"></div>
                    <div className = "blob-2"></div>
                  </div>
                )
            )
          } 
        </div>
      </>)
    })
  }

  return (
    <div className="chat-body">
      <div className="model-select-area">
        <Select onChange={changeModel}
          size="large"
          value={currentModel}
          options={modelList} />
      </div>
      <div className="chat-record-area" ref={chatAreaRef}>
        {renderChatArea()}
      </div>
      <div className="chat-input-area">
        <TextArea
          value={prompt}
          showCount={false}
          maxLength={2000}
          onChange={(e) => setPrompt(e.target.value)}
          placeholder="有什么我能帮您的吗？"
          style={{ resize: 'none' }}
        />
        <div className="operate-area">
          <div className="upload">
            <Button icon={<UploadOutlined />} iconPosition="start">上传文件</Button>
          </div>
          <div className="commit">
            <Button type="primary"
              onClick={sendMessage}
              disabled={isLoading || !currentModel || !prompt.trim()}>
                {isLoading ? '发送中' : '发送'}
            </Button>
          </div>
          {
            isLoading && (
            <Button
              type="primary"
              danger
              onClick={cancelRequest}
              className="cancel"
              icon={<StopOutlined />}
            >
              取消
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}

export default index;
